package com.example.idlefish.HomeAndSearch

import HistoryAdapter
import SearchHistoryManager
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.R
import android.graphics.Color
import android.util.Log
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.helper.widget.Flow
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.pojo.Class_t
import com.example.idlefish.PublicModule.NetworkSettings
import org.json.JSONArray
import org.w3c.dom.Text
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL


class SearchActivity : AppCompatActivity(), OnSubItemClickListener {
    lateinit var del_button : ImageButton
    lateinit var constraintLayout : ConstraintLayout
    lateinit var textViewIds : MutableList<Int>
    lateinit var personList: MutableList<SearchRecord>
    lateinit var searchHistoryManager: SearchHistoryManager
    lateinit var ClassList : MutableList<Class_t>
    val goodContentLauncher = registerForActivityResult(GooddResultContract()){
            result->
        if(result)
        {
            Toast.makeText(this, "成功从详情页返回", Toast.LENGTH_LONG).show()
        }
        else{
            Toast.makeText(this, "详情页返回失败", Toast.LENGTH_LONG).show()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.search_layout)

        val goodContentLauncher = registerForActivityResult(GooddResultContract()){
                result->
            if(result)
            {
                Toast.makeText(this, "成功从详情页返回", Toast.LENGTH_LONG).show()
            }
            else{
                Toast.makeText(this, "详情页返回失败", Toast.LENGTH_LONG).show()
            }
        }
        val originalBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_search_delete)
        val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 40, 50, true)

        // 设置缩放后的图片
        searchHistoryManager = SearchHistoryManager(this)
        del_button = findViewById<ImageButton>(R.id.del_button)
        del_button.setImageBitmap(scaledBitmap)

        val originalBitmap2 = BitmapFactory.decodeResource(resources, R.drawable.ic_search_update)
        val scaledBitmap2 = Bitmap.createScaledBitmap(originalBitmap2, 50, 50, true)

        // 设置缩放后的图片
        val update_button = findViewById<ImageButton>(R.id.update_button)
        update_button.setImageBitmap(scaledBitmap2)

        constraintLayout = findViewById<ConstraintLayout>(R.id.constraintLayout)
        val flow = findViewById<Flow>(R.id.flow)
        textViewIds = mutableListOf<Int>() //  用于存储 TextView 的 ID
        // 重新获取历史记录
        personList = mutableListOf()
        //update
        update_data(constraintLayout, textViewIds, personList, searchHistoryManager, 0)
        // 将 TextView 绑定到 Flow
        flow.referencedIds = textViewIds.toIntArray()
        // 如果需要动态调整布局约束，可以使用 ConstraintSet
        val constraintSet = ConstraintSet()
        constraintSet.clone(constraintLayout)
        constraintSet.applyTo(constraintLayout)
        update_data(constraintLayout, textViewIds, personList, searchHistoryManager, 0)

        del_button.setOnClickListener {
            // 构建一个弹窗
            AlertDialog.Builder(this)
                .setTitle("确认删除") // 弹窗标题
                .setMessage("确定要删除所有历史记录吗？") // 弹窗内容
                .setPositiveButton("确定") { dialog, which ->
                    // 点击“确定”按钮的操作
                    // 清空历史记录
                    searchHistoryManager.clearSearchHistory()
                    update_data(constraintLayout, textViewIds, personList, searchHistoryManager, 0)
                    println("历史记录已删除")
                    Toast.makeText(this, "历史记录已清空", Toast.LENGTH_SHORT).show()
                }
                .setNegativeButton("取消") { dialog, which ->
                    // 点击“取消”按钮的操作
                    println("取消删除操作")
                }
                .create()
                .show()
        }


        val constraintLayout2 = findViewById<ConstraintLayout>(R.id.constraintLayout2)
        val flow2 = findViewById<Flow>(R.id.flow2)
        val textViewIds2 = mutableListOf<Int>() // 用于存储 TextView 的 ID
        val personList2: MutableList<SearchRecord> = mutableListOf()

        ClassList = mutableListOf<Class_t>()
        val Type = findViewById<RecyclerView>(R.id.Type)
        Thread {
            try {
                val urlString = "${NetworkSettings.HTTP}/product/getclass"
                val url = URL(urlString)
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"

                val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()
                val jsonArray = JSONArray(response.toString())
                for (i in 0 until jsonArray.length()) {
                    val obj = jsonArray.getJSONObject(i)
                    val id = obj.getInt("id")
                    val name = obj.getString("name")
                    ClassList.add(
                        Class_t(
                            id = id,
                            name = name
                        )
                    )
                }
                runOnUiThread {
                    // 设置布局管理器

                    val cls = ClassList.take(14).toMutableList()
                    val randomSix = getRandomClasses(cls, 6)
                    Type.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
                    val adapter_type = TypeSheetAdapter(randomSix, { id ->

                        goodContentLauncher.launch(id.toLong())
                    }, Type, this)
                    Type.adapter = adapter_type
                    update_data(constraintLayout2, textViewIds2, personList2, searchHistoryManager,1)
                }


            } catch (e: Exception) {
                Log.e("Product", "Exception occurred: ${e.message}", e)
            }

        }.start()
        println(ClassList)

        val search_button = findViewById<TextView>(R.id.search_button)
        val search_text = findViewById<EditText>(R.id.search_txt)
        search_button.setOnClickListener{
            val txt = search_text.text.toString().trim() // 去掉首尾空格
            if (txt.isNotEmpty()) {
                val searchHistoryManager = SearchHistoryManager(this)
                // 添加搜索记录
                searchHistoryManager.saveSearchRecord(txt)
                //跳转到具体的内容界面
                if (!search_button.text.isNullOrEmpty()) {
                    // TextView 不为空
                    val intent = Intent(this, OneResultActivity::class.java)
                    intent.putExtra("name", search_text.text.toString()) // 传入键值对
                    intent.putExtra("type", 0)
                    startActivity(intent)

                }


            } else {
                // 如果输入为空，可以提示用户（可选）
                println("请输入搜索内容")
            }

        }


        val all_history: TextView = findViewById(R.id.all_history)

        // 设置点击事件
        all_history.setOnClickListener {
            // 创建 BottomSheetDialogFragment 实例

            supportFragmentManager.setFragmentResultListener("BottomSheetDismissed", this) { _, _ ->
                // 在这里执行更新逻辑
                update_data(constraintLayout, textViewIds, personList, searchHistoryManager, 0)
            }
            val bottomSheetFragment = ButtonSheetHistoryFragment()

            bottomSheetFragment.show(supportFragmentManager, bottomSheetFragment.tag)

        }
        update_button.setOnClickListener{
            update_data(constraintLayout2, textViewIds2, personList2, searchHistoryManager,1)
        }

    }

    fun getRandomClasses(clslist: MutableList<Class_t>, count: Int): MutableList<Class_t> {
        //return clslist.shuffled().take(count).toMutableList()
        val trimmedList = clslist.dropLast(1)
        return trimmedList.shuffled().take(count).toMutableList()
    }



    override fun onSubItemClick(parentPosition: Int, childPosition: Int, data: Int) {
        // Toast.makeText(
        //     this,
        //     "Clicked Parent: $parentPosition, Child: $childPosition, Data: $data",
        //     Toast.LENGTH_SHORT
        // ).show()
        goodContentLauncher.launch(data.toLong())
    }
    override fun onResume() {
        super.onResume()
        if (::del_button.isInitialized &&
            ::constraintLayout.isInitialized &&
            ::textViewIds.isInitialized &&
            ::personList.isInitialized &&
            searchHistoryManager != null
        ) {
            update_data(constraintLayout, textViewIds, personList, searchHistoryManager, 0)
        } else {
            Log.e("SearchActivity", "Required data or UI elements are not initialized or personList is empty.")
        }
    }

    fun update_data(
        constraintLayout: ConstraintLayout,
        textViewIds: MutableList<Int>,
        personList: MutableList<SearchRecord>,
        searchHistoryManager: SearchHistoryManager,
        type: Int
    ) {
        constraintLayout.removeAllViews()
        textViewIds.clear()
        var history: MutableList<SearchRecord> = mutableListOf()
        var ranlist: MutableList<Class_t> = mutableListOf()
        if(type == 0)
        {
            var firstTenHistory = searchHistoryManager.loadSearchHistory()
            history = firstTenHistory.take(10).toMutableList()

        }
        else
        {
            //随机获取6个标签

            ranlist =  getRandomClasses(ClassList, 6)
            println(ranlist)
            println("66666666666666666666666")

            for (i in 1..ranlist.size) {
                history.add(SearchRecord(ranlist[i - 1].name, System.currentTimeMillis()))
            }


            //history = searchHistoryManager.loadSearchHistory()
        }


        if (history.isNotEmpty()) {
            // 创建 Flow 布局
            val flow = Flow(constraintLayout.context).apply {
                id = View.generateViewId()
                layoutParams = ConstraintLayout.LayoutParams(
                    ConstraintLayout.LayoutParams.MATCH_PARENT,
                    ConstraintLayout.LayoutParams.WRAP_CONTENT
                )
                setOrientation(Flow.HORIZONTAL)  // 水平排列
                setWrapMode(Flow.WRAP_ALIGNED)   // 每行左对齐
                setHorizontalGap(16)            // 固定水平间距
                setVerticalGap(16)              // 固定垂直间距
            }
            constraintLayout.addView(flow)

            val textViewIdsList = mutableListOf<Int>()

            // 遍历历史记录，添加 TextView
            history.forEach { record ->
                personList.add(SearchRecord(record.content, record.timestamp))

                val textView = TextView(constraintLayout.context).apply {
                    id = View.generateViewId()
                    text = record.content
                    layoutParams = ConstraintLayout.LayoutParams(
                        ConstraintLayout.LayoutParams.WRAP_CONTENT,
                        ConstraintLayout.LayoutParams.WRAP_CONTENT
                    )
                    textSize = 18f
                    setPadding(16, 8, 16, 8)
                    gravity = Gravity.CENTER

                    // 圆角背景
                    background = GradientDrawable().apply {
                        setColor(Color.parseColor("#D3D3D3"))
                        cornerRadius = 16f
                    }
                    setTextColor(Color.BLACK)
                    setOnClickListener {
                        // 这里可以实现点击后的逻辑
                        if(type == 0)
                        {
                            val intent = Intent(constraintLayout.context, OneResultActivity::class.java)
                            intent.putExtra("name", record.content) // 传入键值对
                            intent.putExtra("type", "0")
                            startActivity(intent)
                            val searchHistoryManager = SearchHistoryManager(constraintLayout.context)
                            // 添加搜索记录
                            searchHistoryManager.saveSearchRecord(record.content)
                        }
                        else{
                            val intent = Intent(constraintLayout.context, OneResultActivity::class.java)
                            intent.putExtra("name", record.content) // 传入键值对
                            intent.putExtra("type", "1")
                            startActivity(intent)
                            val searchHistoryManager = SearchHistoryManager(constraintLayout.context)
                            // 添加搜索记录
                            searchHistoryManager.saveSearchRecord(record.content)
                        }
                    }
                }

                constraintLayout.addView(textView)   // 添加 TextView
                textViewIdsList.add(textView.id)     // 收集 ID
                textViewIds.add(textView.id)
            }

            // 将 TextView ID 传递给 Flow
            flow.referencedIds = textViewIdsList.toIntArray()

            // 设置 Flow 的约束
            val constraintSet = ConstraintSet()
            constraintSet.clone(constraintLayout)
            constraintSet.connect(flow.id, ConstraintSet.TOP, constraintLayout.id, ConstraintSet.TOP, 16)
            constraintSet.connect(flow.id, ConstraintSet.START, constraintLayout.id, ConstraintSet.START, 16)
            constraintSet.applyTo(constraintLayout)
        } else {
            // 无历史记录时的默认提示
            val textView = TextView(constraintLayout.context).apply {
                id = View.generateViewId()
                layoutParams = ConstraintLayout.LayoutParams(
                    ConstraintLayout.LayoutParams.WRAP_CONTENT,
                    ConstraintLayout.LayoutParams.WRAP_CONTENT
                )
                text = "当前没有历史记录..."
                textSize = 16f
                setPadding(16, 16, 16, 16)

                gravity = Gravity.CENTER
                setTextColor(Color.BLACK)
            }

            constraintLayout.addView(textView)

            val constraintSet = ConstraintSet()
            constraintSet.clone(constraintLayout)
            constraintSet.connect(textView.id, ConstraintSet.TOP, constraintLayout.id, ConstraintSet.TOP, 16)
            constraintSet.connect(textView.id, ConstraintSet.START, constraintLayout.id, ConstraintSet.START, 16)
            constraintSet.applyTo(constraintLayout)
        }
    }



}